package is.ru.honn.rumblr.factory;

import is.ru.honn.rumblr.data.PostDetail;
import is.ru.honn.rumblr.domain.AbstractRumblrPost;
import is.ru.honn.rumblr.domain.RegularPost;
import is.ru.honn.rumblr.domain.RumblrPost;
import is.ru.honn.rumblr.util.XmlUtil;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class RegularPostFactory extends PostFactory
{

  @Override
  public RumblrPost createPostFromXML(Element e)
  {
    RegularPost post = new RegularPost();
    createHeader(post, e);
    post.setRegularTitle(XmlUtil.getXPathValue(e, "regular-title"));
	post.setRegularBody(XmlUtil.getXPathValue(e, "regular-body"));
    return post;
  }

  @Override
  public List<PostDetail> createPostDetails(AbstractRumblrPost post)
  {
    RegularPost reg = (RegularPost)post;
    List<String> tags = reg.getTags();
    PostDetail postDetail;
    List<PostDetail> postDetails = new ArrayList<PostDetail>();

    postDetail = new PostDetail(reg.getId(), "regular-title", reg.getRegularTitle());
    postDetails.add(postDetail);
    postDetail = new PostDetail(reg.getId(), "regular-body", reg.getRegularBody());
    postDetails.add(postDetail);

    for (String tag : tags)
    {
      postDetail = new PostDetail(reg.getId(), "tag", tag);
      postDetails.add(postDetail);
    }

    return postDetails;

  }
  //Creates a Regular post sets it type and returns it, createPostFromType from postfactory calls this function
  @Override
  public AbstractRumblrPost createPostType(String type)
  {
      RegularPost reg = new RegularPost();
      reg.setType(type);  // Sets the type post
      return reg;
  }

    //Merges the list of details into the post, use a basic for loop for all the items in the list and
   // places them in the right field.
  @Override
  public  AbstractRumblrPost mergeDetailsWithPost(AbstractRumblrPost post, Collection<PostDetail> details)
  {
      RegularPost regular = (RegularPost)post;
      List<String> tags = new ArrayList<String>();
      for(PostDetail dt : details)
      {
          if(dt.getName().equals("regular-title"))
          {
              regular.setRegularTitle(dt.getValue());
          }
          else if(dt.getName().equals("regular-body"))
          {
              regular.setRegularBody(dt.getValue());
          }
          else if (dt.getName().equals("tag"))
          {
              tags.add(dt.getValue());
          }
      }
      regular.addTags(tags);
      return regular;
  }
}
